<template>
  <div class="users-view">
    <h1>👥 用户管理</h1>

    <el-card class="toolbar-card">
      <div class="toolbar">
        <el-input v-model="query.keyword" placeholder="关键词（用户名/邮箱/手机号）" clearable class="w-300" @keyup.enter.native="loadUsers" />
        <el-select v-model="query.size" class="w-120" @change="handleSizeChange">
          <el-option :value="10" label="每页10条" />
          <el-option :value="20" label="每页20条" />
          <el-option :value="50" label="每页50条" />
        </el-select>
        <el-button type="primary" @click="loadUsers" :loading="loading">查询</el-button>
        <el-button @click="resetFilters" :disabled="loading">重置</el-button>
        <el-button type="success" @click="openCreate">新增用户</el-button>
      </div>
    </el-card>

    <el-card>
      <el-table :data="users" border stripe v-loading="loading" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="username" label="用户名" min-width="140" />
        <el-table-column prop="realName" label="姓名" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="180" />
        <el-table-column prop="phone" label="手机号" min-width="140" />
        <el-table-column prop="createdAt" label="注册时间" min-width="160">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="{ row }">
            <el-button size="small" @click="viewUser(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editUser(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeUser(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="query.size"
          :current-page="query.page + 1"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
  <!-- 新增/编辑弹窗 -->
  <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑用户' : '新增用户'" width="600">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="用户名" prop="username"><el-input v-model="form.username" /></el-form-item>
      <el-form-item label="姓名" prop="realName"><el-input v-model="form.realName" /></el-form-item>
      <el-form-item label="邮箱" prop="email"><el-input v-model="form.email" /></el-form-item>
      <el-form-item label="手机号" prop="phone"><el-input v-model="form.phone" /></el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible=false">取消</el-button>
      <el-button type="primary" :loading="saving" @click="submitUser">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { userAPI } from '@/api'

const loading = ref(false)
const users = ref([])
const total = ref(0)
const query = ref({ page: 0, size: 10, keyword: '' })

// 编辑弹窗
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref(null)
const form = ref({ id: null, username: '', realName: '', email: '', phone: '' })
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  realName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  email: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
}

function formatDate(dt) {
  if (!dt) return ''
  const d = new Date(dt)
  return d.toLocaleString('zh-CN')
}

async function loadUsers() {
  try {
    loading.value = true
    const resp = await userAPI.getUserList({ ...query.value })
    const content = resp?.data?.content || resp?.content || resp || []
    users.value = Array.isArray(content) ? content : []
    total.value = resp?.data?.totalElements ?? resp?.totalElements ?? users.value.length
  } catch (err) {
    ElMessage.error(`加载用户失败：${err?.message || '请求错误'}`)
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  query.value = { page: 0, size: 10, keyword: '' }
  loadUsers()
}

function handleSizeChange() {
  query.value.page = 0
  loadUsers()
}

function handlePageChange(p) {
  query.value.page = p - 1
  loadUsers()
}

function viewUser(row) { ElMessage.info(`查看用户：${row.username}`) }
function editUser(row) {
  isEdit.value = true
  form.value = { id: row.id, username: row.username, realName: row.realName, email: row.email, phone: row.phone }
  dialogVisible.value = true
}
function openCreate() {
  isEdit.value = false
  form.value = { id: null, username: '', realName: '', email: '', phone: '' }
  dialogVisible.value = true
}
async function submitUser() {
  try {
    await formRef.value.validate()
    saving.value = true
    if (isEdit.value && form.value.id) {
      await userAPI.updateUser(form.value.id, { ...form.value })
      ElMessage.success('用户已更新')
    } else {
      await userAPI.createUser({ ...form.value })
      ElMessage.success('用户已创建')
    }
    dialogVisible.value = false
    loadUsers()
  } catch (err) {
    ElMessage.error(err?.message || '保存失败')
  } finally {
    saving.value = false
  }
}
async function removeUser(row) {
  try {
    await ElMessageBox.confirm(`确认删除用户「${row.username}」吗？`, '提示', { type: 'warning' })
    await userAPI.deleteUser(row.id)
    ElMessage.success('已删除')
    loadUsers()
  } catch (err) {
    if (String(err).includes('cancel')) return
    ElMessage.error(err?.message || '删除失败')
  }
}

onMounted(loadUsers)
</script>

<style scoped>
.users-view { padding: 20px; }
.toolbar-card { margin-bottom: 12px; }
.toolbar { display: flex; gap: 12px; align-items: center; }
.w-300 { width: 300px; }
.w-120 { width: 120px; }
.table-footer { display: flex; justify-content: flex-end; padding-top: 12px; }
</style>